package org.wesc.boot.service.system.notice;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.wesc.boot.common.constant.CommonConstant;
import org.wesc.boot.dao.domain.QueryRequest;
import org.wesc.boot.dao.entity.Notice;
import org.wesc.boot.dao.entity.User;
import org.wesc.boot.dao.entity.UserMessage;
import org.wesc.boot.dao.mapper.NoticeMapper;
import org.wesc.boot.dao.model.UserMessageModel;
import org.wesc.boot.dao.querymapper.UserMessageQueryMapper;
import org.wesc.boot.dao.service.NoticeService;
import org.wesc.boot.dao.service.UserMessageService;
import org.wesc.boot.dao.utils.SortUtil;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 用户消息高级服务
 *
 * @author Wesley
 * @date 2021/4/1
 */
@Slf4j
@Service
public class UserMessageAdvanceService {

    private final UserMessageQueryMapper userMessageQueryMapper;

    private final UserMessageService userMessageService;

    private final NoticeMapper noticeMapper;

    private final NoticeService noticeService;

    @Autowired
    public UserMessageAdvanceService(UserMessageQueryMapper userMessageQueryMapper,
                                     UserMessageService userMessageService,
                                     NoticeMapper noticeMapper,
                                     NoticeService noticeService) {
        this.userMessageQueryMapper = userMessageQueryMapper;
        this.userMessageService = userMessageService;
        this.noticeMapper = noticeMapper;
        this.noticeService = noticeService;
    }

    /**
     * 分页查询用户消息
     */
    public IPage<UserMessageModel> pageQueryList(QueryRequest request, UserMessageModel userMessageModel) {
        Page<UserMessageModel> page = new Page<>();
        List<UserMessageModel> resultList = this.userMessageQueryMapper.getUserMessageList(userMessageModel);
        SortUtil.handlePageSort(request, page, true);
        page.setRecords(resultList);
        return page;
    }

    /**
     * 将ALL类型系统通告补充到用户消息阅读标记表中: 未删除、已发布, 且新注册用户不看结束通知
     *
     * @param currentUser 当前用户
     */
    @Transactional(rollbackFor = Exception.class)
    public void fillUserMessage(User currentUser) {
        String userId = String.valueOf(currentUser.getUserId());
        LambdaQueryWrapper<Notice> allWrapper = new LambdaQueryWrapper<>();
        allWrapper.eq(Notice::getMsgType, INoticeConstant.MSG_TYPE_ALL);
        allWrapper.eq(Notice::getDelFlag, CommonConstant.DEL_FLAG_0.toString());
        allWrapper.eq(Notice::getSendStatus, INoticeConstant.PUBLISHED_STATUS_1);
        allWrapper.ge(Notice::getEndTime, currentUser.getCreateTime());
        allWrapper.notInSql(Notice::getId, "select notice_id from sys_user_message where user_id='" + userId + "'");
        List<Notice> notices = this.noticeService.list(allWrapper);

        if (notices.size() > 0) {
            for (Notice notice : notices) {
                // 因为websocket没有判断是否存在这个用户，要是判断会出现问题，故在此判断逻辑
                LambdaQueryWrapper<UserMessage> query = new LambdaQueryWrapper<>();
                query.eq(UserMessage::getNoticeId, notice.getId());
                query.eq(UserMessage::getUserId, userId);
                UserMessage one = this.userMessageService.getOne(query);
                if (null == one) {
                    UserMessage userMessage = new UserMessage();
                    userMessage.setNoticeId(notice.getId());
                    userMessage.setUserId(userId);
                    userMessage.setReadFlag(INoticeConstant.NO_READ_FLAG);
                    this.userMessageService.save(userMessage);
                }
            }
        }
    }

    /**
     * 更新用户消息阅读状态
     *
     * @param noticeId noticeId
     * @param userId userId
     */
    @Transactional(rollbackFor = Exception.class)
    public void updateMessageReadFlag(String noticeId, String userId) {
        LambdaUpdateWrapper<UserMessage> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.set(UserMessage::getReadFlag, INoticeConstant.HAS_READ_FLAG);
        updateWrapper.set(UserMessage::getReadTime, LocalDateTime.now());
        updateWrapper.last("where notice_id ='" + noticeId + "' and user_id ='" + userId + "'");
        UserMessage userMessage = new UserMessage();
        this.userMessageService.update(userMessage, updateWrapper);
    }

    /**
     * 一键已读
     *
     * @param userId userId
     */
    @Transactional(rollbackFor = Exception.class)
    public void readAll(String userId) {
        LambdaUpdateWrapper<UserMessage> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.set(UserMessage::getReadFlag, INoticeConstant.HAS_READ_FLAG);
        updateWrapper.set(UserMessage::getReadTime, LocalDateTime.now());
        updateWrapper.last("where user_id ='"+userId+"'");
        UserMessage userMessage = new UserMessage();
        this.userMessageService.update(userMessage, updateWrapper);
    }

    /**
     * 查询用户未读的系统消息
     */
    public List<Notice> queryUnreadListByUserId(String userId) {
        return this.noticeMapper.queryUnreadListByUserId(userId);
    }

    /**
     * 通过id查询消息
     * @param id id
     * @return 消息
     */
    public UserMessage queryById(String id) {
        return this.userMessageService.getById(id);
    }

}
